package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

	@Override
	public List<CategoryEntity> listWithTree() {
		QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
		// queryWrapper.isNotNull("sort");
		List<CategoryEntity> entities = baseMapper.selectList(queryWrapper);
		CategoryEntity root = new CategoryEntity();
		root.setCatId(0L);
		return getChildrens(root, entities);
	}

	@Override
	public void removeMenuByIds(List<Long> asList) {

		baseMapper.deleteBatchIds(asList);
	}

	private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
    	return all.stream().filter(c -> c.getParentCid().equals(root.getCatId())).peek(c -> c.setChildren(getChildrens(c, all))).sorted(Comparator.comparing(CategoryEntity::getSort, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
	}
}